// 引入vue
import Vue from 'vue'
// 引入vuex
import Vuex from 'vuex'
// 使用vuex
Vue.use(Vuex)

import { shopType, tableInfo } from '@/api/modules/index.js'
import { BASE_URL_IMG } from "@/api/config"

// 准备state,用于存储数据
const state = {
    sideList:[ // 侧边栏数据
    ],
    sideBarId: -1, // 侧边栏选中id
    indexList: [
    ],
    sidebarBool: true,  // 侧边栏 显示和隐藏
    keysearch: '', // 顶部搜索字段
    pageindex: 1,
    pagesize: 10,  // 一次请求 10 条数据
    totalCount: 0, // 一共多少条数据
    // 下拉框
    KehuList: [], // 客户信息
    kdPersonList: [], // 开单业务
    gradeList: [], // 客户等级
    areaList: [],  // 所属区域
    queryList: [],  // 收款账户
    receivePayList: [], // 收款类型
    receiveWayList: [], // 收款方式
    dictionList: [],  // 附加说明
    // 下拉框

    // shopCarList: [], // 购物车  // { num: 1, xsprice: 10.1234, description: '111名称' }
    // cloneShopCarList: [], // 搜索时，占时存放的地方
    shopCarList: uni.getStorageSync('shopCarList').length ? JSON.parse(uni.getStorageSync('shopCarList')) : [], 
    cloneShopCarList: uni.getStorageSync('shopCarList').length ? JSON.parse(uni.getStorageSync('shopCarList')) : [], // 搜索时，占时存放的地方
    author: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).name : '', // 当前登录的人
    // expire_time: 1713087625184, // 后端返回的时间搓  过期
    expire_time: 1723087625184, // 后端返回的时间搓

    // 本地存储 头部关键词  '盒装', '圆形', '不规则', '方形', '心形', '宫廷形', '蛋形', '电视'
    KeywordsList: uni.getStorageSync('localKeywords') ? JSON.parse(uni.getStorageSync('localKeywords')) : [],
    selectAll: false // 全选
}
// 准备mutations,用于操作数据（state）
const mutations = {
    getAuthor(state, payload) { // 获取用户信息
        state.author = payload.author.name
        state.shopCarList = payload.carList
    },
    loginAuthor(state, payload) {
        state.author = payload
    },
    handleActive(state, index) { // 侧边栏高亮显示
        state.sideList = JSON.parse(JSON.stringify(state.sideList)).map((i,j) => ({...i, active: index == j ? true : false}))
        state.pageindex = 1
        state.indexList = []
    },
    getSideData(state, payload) { // 获取侧边栏数据
        state.sideList = payload;
    },
    handleHideSidebar(state, payload) { // 侧边栏显示隐藏
        state.sidebarBool = !payload
    },
    getClearInput(state, payload) { // 清除 input 数据
        state.keysearch = ''
    },
    getSearch(state, payload) { // 获取顶部input字段
        state.keysearch = payload
        state.pageindex = 1
        state.indexList = []

        let localKeywords = uni.getStorageSync('localKeywords') ? JSON.parse(uni.getStorageSync('localKeywords')) : state.KeywordsList;

        if (!localKeywords.includes(payload) && payload) {

            localKeywords.unshift(payload)
            if (localKeywords.length > 10) {
                localKeywords.pop()
            }
            state.KeywordsList = localKeywords
            uni.setStorageSync('localKeywords', JSON.stringify(localKeywords))
        }
    },
    clearHistoryRecord(state, payload) {
        state.KeywordsList = []
        uni.removeStorageSync('localKeywords')
    },
    unloadPage(state, payload) {
        state.pageindex = 1
        state.indexList = []
    },
    getSidebarId(state, payload) {
        state.sideBarId = payload
    },
    getTableData(state, payload) { // 修改数组
        const { data, keysearch, type } = payload
        const { list, totalCount, totalPage } = data || {}

        if (!list.length) {
            uni.showToast({
                title: '暂无数据!',
                duration: 2000,
                icon: 'none'
            });
        }

        let newList = (list || []).map(i => ({
            ...i, 
            files: i.files.map(j => ({
                ...j,
                imgurl: `${BASE_URL_IMG}${j.imgurl}`,
                url: `${BASE_URL_IMG}${j.url}`
            }))
        }))

        // console.log('=== newList', newList)

        // console.log('== 总', totalCount / 20,  Math.ceil(totalCount / 20), '==',  state.pageindex)

        // if (type && (state.pageindex >  Math.ceil(totalCount / 20) )) {
        //     uni.showToast({
        //         title: '数据以加载完毕!',
        //         duration: 2000,
        //         icon: 'none'
        //     });
        //     return
        // }   
        state.totalCount = Math.ceil(totalCount / state.pagesize)
        state.indexList = newList
        // state.indexList = state.indexList.concat(newList)
        // state.pageindex++;
    },

    //  下拉选择框
    comKehu(state, payload) {
        state.KehuList = payload
    },
    comKdPerson(state, payload) {
        state.kdPersonList = payload
    },
    comGrad(state, payload) {
        state.gradeList = payload
    },
    comQuery(state, payload) {
        state.queryList = payload
    },
    comCollectType(state, payload) { // 收款类型
        state.receivePayList = payload
    },
    comCollectWay(state, payload) { // 收款方式
        state.receiveWayList = payload
    },
    comDiction(state, payload) {
        state.dictionList = payload
    },
    //  下拉选择框

    // 购物车页面
    addShopCar(state, payload) { // 数据添加到购物车
        if (state.shopCarList.length == 0) {
            state.shopCarList = payload
        } else {
            let dataMap = new Map(); // 使用Map来存储data中的对象，以便快速查找  
            state.shopCarList.forEach(dataItem => {  
                dataMap.set(JSON.stringify({  
                    id: dataItem.id,  
                }), dataItem);  
            });  

            payload.forEach(item => {  
                let key = JSON.stringify({  
                    id: item.id,  
                });  
                let dataItem = dataMap.get(key);  
                if (dataItem) {  
                    // 如果在data中找到了匹配的对象，更新num  
                    if (!!dataItem.num) {  
                        // dataItem.num++; 
                        dataItem.num += item.num
                    }  
                    // 查找this.data中是否已经存在该对象  
                    let existingItem = state.shopCarList.find(d => {  
                        return (  
                            d.id === item.id  
                        );  
                    });  
                    if (existingItem) {  
                        // 如果存在，更新num  
                        existingItem.num = dataItem.num;  
                        existingItem.sl = dataItem.sl;  
                    } else {  
                        // 如果不存在，添加新对象  
                        state.shopCarList.push({ ...item, num: dataItem.num, sl: dataItem.sl });  
                    }  
                } else {  
                    // 如果在data中未找到匹配的对象，添加新对象
                    state.shopCarList.push({ ...item });  
                }  
            }); 

        }

        state.cloneShopCarList = state.shopCarList

        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))

        uni.showToast({
            title: '成功加入购物车',
            icon: 'none',
            duration: 3000
        })

    },
    changeRadio(state, index) { // 单选
        state.shopCarList = JSON.parse(JSON.stringify(state.shopCarList)).map((i, j) => ({...i, check: j === index ? !i.check : i.check}))
    },
    changeRadioGift(state, index) {  // 赠品
        state.shopCarList = JSON.parse(JSON.stringify(state.shopCarList)).map((i, j) => ({
            ...i, 
            showGift: j === index ? !i.showGift : i.showGift,
            wholesale: j === index ? 0 : i.wholesale,
        }))

        state.cloneShopCarList = state.shopCarList
        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))
    },
    changeAllRadio(state, payload) { // 全选
        state.selectAll = !state.selectAll
        state.shopCarList = JSON.parse(JSON.stringify(state.shopCarList)).map((i, j) => ({...i, check: state.selectAll }))
    },
    changeEdit(state, type) {
        state.selectAll = type
    },
    deleteShop(state, payload) { // 删除商品
        state.shopCarList = JSON.parse(JSON.stringify(state.shopCarList)).filter((i, j) => i.check != true)
        state.cloneShopCarList = state.shopCarList
        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))
        uni.showToast({
            title: '删除成功!',
            icon: 'none',
            duration: 3000
        })
    },
    clearShopCar(state, payload) { // 清空购物车
        state.shopCarList = [];
        state.cloneShopCarList = [];
        uni.setStorageSync('shopCarList', [])
        // uni.showToast({
        //     title: '购物车已清空',
        //     icon: 'none',
        //     duration: 3000
        // })
    },
    changeFieldShopCar(state, payload) {
        const { index, target, type } = payload
        let data = JSON.parse(JSON.stringify(state.shopCarList))
        // state.shopCarList = data.map((i, j) => ({...i, num: index == j ? num : i.num }))
        state.shopCarList = data.map((i, j) => ({...i, [type]: index == j ? target : i[type] }))
        state.cloneShopCarList = state.shopCarList
        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))
    },
    addNumShopCar(state, payload){ // +1
        let data = JSON.parse(JSON.stringify(state.shopCarList))
        state.shopCarList = data.map((i, j) => ({...i, num: payload == j ? (Number(i.num) + 1) : i.num}))
        state.cloneShopCarList = state.shopCarList
        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))
    },
    minuaNumShopCar(state, payload){ // -1
        if (state.shopCarList[payload].num <= 1) {
            return
        }
        let data = JSON.parse(JSON.stringify(state.shopCarList))
        state.shopCarList = data.map((i, j) => ({...i, num: payload == j ? (Number(i.num) - 1) : i.num}))

        // console.log('=== ---', state.shopCarList[1].num)
        state.cloneShopCarList = state.shopCarList
        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))
    },
    deleteShopCarItem(state, payload) { // 删除
        let data = JSON.parse(JSON.stringify(state.shopCarList))
        state.shopCarList = data.filter((i, j) => j != payload)
        state.cloneShopCarList = state.shopCarList
        uni.setStorageSync('shopCarList', JSON.stringify(state.shopCarList))
        uni.showToast({
            title: '删除成功!',
            icon: 'none',
            duration: 3000
        })
    },
    searchShopCar(state, payload) {  // 订单页面模糊搜索
        if (payload) {
            state.shopCarList = state.cloneShopCarList.filter(i => i.name.includes(payload))
        } else {
            state.shopCarList = state.cloneShopCarList
        }
    },
    // 购物车
}

// 准备actions,用于响应组件中的动作
const actions = {
    async getTableDataAct({commit, state }, obj) { // 获取顶部input字段
        state.pageindex = obj.pageIndex
        const { keysearch, pageindex, pagesize, sideList } = state
        let param = {
            paging: {
                pageIndex: pageindex,
                pageSize: pagesize,
            },
            query: {
                type_nos: ['cp', 'bcp', 'yl'],
                valid: true,
                cate_id: obj.id,
                search: keysearch, // 搜索字段
            },
        }
        const res = await tableInfo(JSON.stringify(param))
        const {  data: { status, data: { paging, materiels }, message }  } = res || {}
        let newData = {
            list: materiels,
            totalCount: paging.total,
            totalPage: paging.pageIndex,
        }

        if (status == 'success') {
            commit('getTableData', {data: newData})
            // if (materiels.length == 0) {
            //     uni.showToast({
            //         title: '暂无数据',
            //         duration: 2000,
            //         icon: 'none'
            //     })
            // }
        } else if (status === 'fail') {
            uni.showToast({
        		title: message,
        		duration: 2000,
        		icon: 'none'
        	});
        } 

    }
}

const getters = {
    sumCom(state ) {
        return (state.shopCarList || []).reduce((a, b) => a += Number(b.num), 0)
    },
    amountCom(state ) {
        return (state.shopCarList || []).reduce((a, b) => {
            let sum =( b.num * ( b.wholesale * 100000000 )) / 100000000
            if (b.hasOwnProperty('wholesale')) {
                return ((a * 10000000) + (sum * 10000000)) / 10000000;
            } else {
                return (a * 10000000) / 10000000
            }
        }, 0)
    },
}

// 创建并暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})
